package com.center.growcenterserver.interceptor;

import com.center.growcenterserver.common.JwtUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 预处理，在业务处理器处理请求之前被调用，可以进行登录拦截，编码处理、安全控制、权限校验等处。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是http option请求，如果是就放行
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        //验证
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
            //抛出异常，项目进行全局异常处理
        }
        return true;
    }
}